package com.cqvip.innocence.framework.config.aspect;

import com.cqvip.innocence.common.annotation.AvoidRepeatSubmit;
import com.cqvip.innocence.common.util.redis.RedisService;
import com.cqvip.innocence.project.model.dto.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 重复提交相关切面
 *
 * @author 01
 * @date 2022-05-25 11:27
 */
@Slf4j(topic = "AvoidRepeatSubmitAspect")
@Aspect
@Component
public class AvoidRepeatSubmitAspect extends AbstractAspect<AvoidRepeatSubmit> {

    @Autowired
    RedisService redisService;

    @Around("@annotation(com.cqvip.innocence.common.annotation.AvoidRepeatSubmit)")
    public Object aroundAdvice(ProceedingJoinPoint pjp) {
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        AvoidRepeatSubmit annotation = method.getAnnotation(AvoidRepeatSubmit.class);
        //注解参数 s
        int interval = annotation.interval();
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
            HttpServletRequest request = attributes.getRequest();
            String key = sessionId + "-" + request.getServletPath();
            if (redisService.get(key) == null) {
                Object proceed = pjp.proceed();
                redisService.set(key, "", (long) interval, TimeUnit.MILLISECONDS);
                return proceed;
            } else {
                //log.error("重复提交");
                return new JsonResult(false, "请勿重复提交！");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            log.error("验证重复提交时出现未知异常!");
            return new JsonResult(false, "请勿重复提交！");
        }
    }
}
